package top.zhaojx.rpc.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.zhaojx.rpc.factory.ThreadPoolFactory;
import top.zhaojx.rpc.util.NacosUtil;

/**
 * 系统下线时提供的钩子,主要通过{NacosUtil.clearRegistry()}清除所有注册信息
 */
public class ShutdownHook {
    private static final Logger logger = LoggerFactory.getLogger(ShutdownHook.class);

    private ShutdownHook() {}

    private static volatile ShutdownHook shutdownHook  = null;

    public static ShutdownHook getShutdownHook() {
        if(shutdownHook == null) {
            synchronized (ShutdownHook.class) {
                if(shutdownHook == null) {
                    shutdownHook = new ShutdownHook();
                }
            }
        }
        return shutdownHook;
    }

    public void addClearAllHook() {
        logger.info("关闭后将自动注销所有服务");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            NacosUtil.clearRegistry();
            ThreadPoolFactory.shutDownAll();
        }));
    }
}
